<template>
  <div>
    <UploadExcel
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>
<script>
import { formatDate } from '@/utils/data'
import { importEmployee } from '@/api/employees'
export default {
  data() {
    return {

    }
  },
  created() {

  },
  mounted() {

  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
    //   this.tableData = results
    //   this.tableHeader = header
      try {
        console.log(results, header)
        const res = this.transExcelHander(results)
        console.log('转换后的数据', res)
        const rs = await importEmployee(res)
        console.log('文件上传返回数据', rs)
        this.$router.back()
        this.$message.success(rs.data.message)
      } catch (error) {
        console.log(error)
      }
    },
    // 转换Excel返回信息
    transExcelHander(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const newArr = results.map(item => {
        const userInfo = {}
        for (const key in item) {
          console.log('key值为====', key)
          const newKey = userRelations[key]
          userInfo[newKey] = item[key]
          if (['correctionTime', 'timeOfEntry'].includes(newKey)) {
            // 需要对key对应的value做时间处理
            // 严格来讲需要使用与excel插件配套的时间处理函数 处理成标准的时间Date格式
            // 后端接口才能识别
            userInfo[newKey] = new Date(formatDate(item[key]))
          }
        }
        return userInfo
      })
      console.log(newArr)
      return newArr
    }
  }
}
</script>

<style scoped>

</style>
